# _*_coding:utf-8_*_

import time
from ATS.instrumentDriver import InstCom as inst
from ATS.datamanager.DataManager import DataManager


# add markers for ENA
def marksetup(source, marknum):
    for i in range(1, marknum + 1):
        inst.write(source, ":CALC:MARK%s:ACT" % i)


# search the center frequency
def marksearch(source):
    buf = []
    inst.write(source, ":CALC1:MARK1:FUNC:TYPE MAX")
    inst.write(source, ":CALC1:MARK1:FUNC:EXEC")
    inst.write(source, ":CALC1:MARK1:BWID:THR -3")
    inst.write(source, ":CALC1:MARK1:BWID:DATA?")
    rst = inst.read(source).split(",")
    for i in rst:
        buf.append(i)
    return buf


def read_trace(cavre_num):
    print("read_trace")


def sweepsetup(source, sweeplist, parament, power=0, ifbandwidth=7E5, sweeptype="LIN"):
    start, stop, point = sweeplist
    inst.write(source, ":CALC:PAR:COUN %s" % len(parament))
    for i in range(0, len(parament)):
        inst.write(source, ":CALC:PAR%s:DEF %s" % (i + 1, parament[i]))

    inst.write(source, ":SENS:FREQ:STAR %s" % start)
    inst.write(source, ":SENS:FREQ:STOP %s" % stop)
    inst.write(source, ":SENS:SWE:POIN %s" % point)
    inst.write(source, ":SOUR:POW %s" % power)
    inst.write(source, ":SENS:SWE:TYPE %s" % sweeptype)
    inst.write(source, ":SENS:BWID %s" % ifbandwidth)
    time.sleep(1)
    marksetup(source, 3)
    buf = marksearch(source)
    __postdata("CF", buf)


def __postdata(name, mylist):
    print("**********", name, mylist)
    DataManager().postarraydata(name, mylist)
